﻿using System;
using System.Collections.Generic;
using System.Linq;
using Grundy.Entity;
using Grundy.Message;

namespace Grundy.Administration.Web.Services
{
    public class ProductService
    {
        public EntitlementsDatabase Db { get; private set; }

        public ProductService()
        {
            Db = new EntitlementsDatabase("EntitlementsDatabase");
        }

        public ProductService(EntitlementsDatabase db)
        {
            Db = db;
        }

        public IQueryable<Product> GetProducts(int page = 1, int pageSize = 0)
        {
            if (page == 1 && pageSize == 0)
                return Db.Products.OrderBy(i => i.Name);
            return Db.Products.OrderBy(i => i.Name).Skip((page - 1) * pageSize).Take(pageSize);
        }

        public Product GetProduct(Guid id)
        {
            return Db.Products.Find(id);
        }

        public Product GetProduct(string name)
        {
            return Db.Products.FirstOrDefault(f => f.Name == name);
        }

        public Product CreateProduct(string name, IEnumerable<Feature> features)
        {
            var product = new Product { Name = name };
            Db.Products.Add(product);
            product.Features = new FeatureCollection(features);
            Db.SaveChanges();
            return product;
        }
    }
}